import { defineStore } from "pinia";
import piniaPersistConfig from "@/stores/helper/persist";
import type { Space } from "@/api/interface/space";
import type { Doc } from "@/api/interface/doc";
import type { Comment } from "@/api/interface/comment";
import { getDocTreeApi, addDocNodeApi, updateDocNodeApi, deleteDocNodeApi, addReadHistoryApi } from "@/api/modules/doc";

import { getSpaceDetailApi, toggleFavoriteApi, checkSpaceAdminApi } from "@/api/modules/space";
import { getCommentsApi, addCommentApi, deleteCommentApi } from "@/api/modules/comment";

import { findNodeById, findFirstDoc, deleteNodeFromTree } from "@/utils/document";

// 定义状态类型
interface DocumentState {
  // 当前空间信息
  currentSpace: Space.SpaceItem;
  // 文档树结构
  docTree: Doc.DocNode[];
  // 当前文档ID
  currentDocId: string;
  // 评论列表
  comments: Comment.CommentItem[];
  // 目录项
  tocItems: Array<{ id: string; text: string; level: number }>;
  // 当前激活的目录项ID
  activeTocId: string;
  // 滚动位置
  scrollPosition: number;
  // 是否显示评论面板
  showCommentPanel: boolean;
  // 是否显示目录
  showToc: boolean;
  // 加载状态
  loading: boolean;
  treeLoading: boolean;
  favoriteLoading: boolean;
  commentLoading: boolean;
  // 当前评论内容
  commentText: string;
  isAdmin: boolean;
}

export const useDocumentStore = defineStore({
  id: "BH-document",
  state: (): DocumentState => ({
    currentSpace: {
      FId: "",
      FTitle: "",
      FDescription: "",
      FIsStarred: false
    } as Space.SpaceItem,
    docTree: [],
    currentDocId: "",
    comments: [],
    tocItems: [],
    activeTocId: "",
    scrollPosition: 0,
    showCommentPanel: false,
    showToc: true,
    loading: false,
    treeLoading: false,
    favoriteLoading: false,
    commentLoading: false,
    commentText: "",
    isAdmin: false
  }),
  getters: {
    // 获取当前文档详情
    currentDoc: state => {
      if (!state.currentDocId) return null;

      function findDoc(nodes: Doc.DocNode[]): Doc.DocNode | null {
        for (const node of nodes) {
          if (node.FId === state.currentDocId && node.FType === "doc") {
            return node;
          }
          if (node.children?.length) {
            const found = findDoc(node.children);
            if (found) return found;
          }
        }
        return null;
      }

      return findDoc(state.docTree);
    },
    // 获取扁平化的文档列表（用于搜索等）
    flatDocList: state => {
      const flatten = (nodes: Doc.DocNode[]): Doc.DocNode[] => {
        return nodes.reduce<Doc.DocNode[]>((acc, node) => {
          acc.push(node);
          if (node.children) {
            acc.push(...flatten(node.children));
          }
          return acc;
        }, []);
      };
      return flatten(state.docTree);
    },
    // 获取当前空间是否已收藏
    isFavorite: state => state.currentSpace?.FIsStarred || false
  },
  actions: {
    async initData() {
      this.$reset();
    },

    // 加载空间详情
    async loadSpaceDetail(spaceId: string) {
      try {
        this.loading = true;
        const { data } = await getSpaceDetailApi({ FId: spaceId });
        this.currentSpace = data;
      } catch (error) {
        console.error("加载空间详情失败:", error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    async checkSpaceAdmin() {
      if (!this.currentSpace?.FId) return false;

      try {
        const { data } = await checkSpaceAdminApi({
          FSpaceId: this.currentSpace.FId
        });
        this.isAdmin = data.isAdmin;
      } catch (error) {
        console.error("检查管理员状态失败:", error);
        this.isAdmin = false;
      }
    },

    // 加载文档树
    async loadDocTree(spaceId: string) {
      try {
        this.treeLoading = true;
        const { data } = await getDocTreeApi({ FSpaceId: spaceId, isAdmin: this.isAdmin });
        this.docTree = data;

        // 如果没有当前文档ID，自动选择第一个文档
        if (!this.currentDocId) {
          const firstDoc = findFirstDoc(this.docTree);
          if (firstDoc) {
            this.currentDocId = firstDoc.FId;
            // 首次加载时添加阅读记录
            await this.addReadHistory(firstDoc.FId);
          }
        }
      } catch (error) {
        console.error("加载文档树失败:", error);
        throw error;
      } finally {
        this.treeLoading = false;
      }
    },

    // 添加阅读记录
    async addReadHistory(FDocId: string) {
      try {
        if (!this.isAdmin) {
          // 管理员不需要记录
          await addReadHistoryApi({ FDocId });

          // 更新本地文档树的浏览次数
          const node = findNodeById(this.docTree, FDocId);
          if (node) {
            node.FViews = (node.FViews || 0) + 1;
          }
        }
      } catch (error) {
        console.error("添加阅读记录失败:", error);
      }
    },

    // 加载评论
    async loadComments(docId: string) {
      try {
        this.commentLoading = true;
        const { data } = await getCommentsApi({ FDocId: docId });
        this.comments = data;
      } catch (error) {
        console.error("加载评论失败:", error);
        throw error;
      } finally {
        this.commentLoading = false;
      }
    },

    // 切换收藏状态
    async toggleFavorite(userId: string) {
      if (!this.currentSpace?.FId) return;

      try {
        this.favoriteLoading = true;
        const params = {
          FSpaceId: this.currentSpace.FId,
          FUserId: userId,
          FIsStarred: !this.currentSpace.FIsStarred
        };

        await toggleFavoriteApi(params);
        if (this.currentSpace) {
          this.currentSpace.FIsStarred = !this.currentSpace.FIsStarred;
        }
      } catch (error) {
        console.error("收藏操作失败:", error);
        throw error;
      } finally {
        this.favoriteLoading = false;
      }
    },

    // 添加文档节点
    async addDocNode(params: {
      FSpaceId: string;
      FParentId?: string;
      FTitle: string;
      FType: Doc.DocType;
      FContent: string;
      FAuthorId: string;
    }) {
      try {
        const { data } = await addDocNodeApi(params);

        const newNode: Doc.DocNode = {
          FId: data.FId,
          FSpaceId: params.FSpaceId,
          FParentId: params.FParentId,
          FTitle: params.FTitle,
          FType: params.FType,
          FCreatedAt: new Date().toISOString(),
          FUpdatedAt: new Date().toISOString(),
          children: []
        };

        if (!params.FParentId) {
          this.docTree.push(newNode);
        } else {
          const parent = findNodeById(this.docTree, params.FParentId);
          parent?.children?.push(newNode);
        }

        return data.FId;
      } catch (error) {
        console.error("添加文档节点失败:", error);
        throw error;
      }
    },

    // 更新文档节点
    async updateDocNode(params: { FId: string; FTitle: string; FContent: string; isAdmin?: boolean }) {
      try {
        await updateDocNodeApi(params);

        const node = findNodeById(this.docTree, params.FId);
        if (node) {
          node.FTitle = params.FTitle;
          node.FContent = params.FContent;
          node.FUpdatedAt = new Date().toISOString();
        }
      } catch (error) {
        console.error("更新文档节点失败:", error);
        throw error;
      }
    },

    // 删除文档节点
    async deleteDocNode(nodeId: string) {
      try {
        await deleteDocNodeApi({ FId: nodeId });
        deleteNodeFromTree(this.docTree, nodeId);

        // 如果删除的是当前文档，选择另一个文档
        if (this.currentDocId === nodeId) {
          const firstDoc = findFirstDoc(this.docTree);
          this.currentDocId = firstDoc?.FId || "";
        }
      } catch (error) {
        console.error("删除文档节点失败:", error);
        throw error;
      }
    },

    // 提交评论
    async submitComment(userId: string) {
      if (!this.commentText.trim()) {
        throw new Error("评论内容不能为空");
      }
      if (!this.currentDocId) {
        throw new Error("没有当前文档");
      }

      try {
        this.commentLoading = true;
        const params = {
          FDocId: this.currentDocId,
          FUserId: userId,
          FContent: this.commentText
        };

        await addCommentApi(params);
        await this.loadComments(this.currentDocId);

        this.commentText = "";
      } catch (error) {
        console.error("提交评论失败:", error);
        throw error;
      } finally {
        this.commentLoading = false;
      }
    },

    // 删除评论
    async deleteComment(commentId: string) {
      try {
        await deleteCommentApi({ FId: commentId });
        this.comments = this.comments.filter(c => c.FId !== commentId);
      } catch (error) {
        console.error("删除评论失败:", error);
        throw error;
      }
    },

    // 设置目录项
    setTocItems(items: Array<{ id: string; text: string; level: number }>) {
      this.tocItems = items;
      if (items.length > 0) {
        this.activeTocId = items[0].id;
      }
    },

    // 设置滚动位置
    setScrollPosition(position: number) {
      this.scrollPosition = position;
    },

    // 重置状态
    reset() {
      this.$reset();
    }
  },
  persist: piniaPersistConfig("BH-document")
});
